using System.Collections.Generic;
using System.IO;
using System.Net;
using Dimebrain.TweetSharp.Core.Extensions;

namespace Dimebrain.TweetSharp.Core.Web.Query
{
    partial class WebQueryBase
    {
        protected virtual string ExecuteGet(string url)
        {
            Response = null;

            var client = CreateWebQueryClient();
            var requestArgs = new WebQueryRequestEventArgs(url);
            OnQueryRequest(requestArgs);

            try
            {
                using (var stream = client.OpenRead(url))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (WebException ex)
            {
                return HandleWebException(ex);
            }
            finally
            {
                Response = client.Response;
            }
        }

        public static string QuickGet(string url)
        {
            return QuickGet(url, null, null, null);
        }

        public static string QuickGet(string url, string username, string password)
        {
            return QuickGet(url, null, username, password);
        }

        public static string QuickGet(string url, IDictionary<string, string> headers, string username, string password)
        {
            var client = CreateWebQueryClient(headers, null, null, false, null, true);

            if(!username.IsNullOrBlank() && !password.IsNullOrBlank())
            {
                client.Credentials = new NetworkCredential(username, password);
            }

            try
            {
                using (var stream = client.OpenRead(url))
                {
                    using (var reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (WebException)
            {
                return null;
            }
        }
    }
}